# -*- coding:utf-8 -*-
# @Author : mistchan
# @Time : 2021/4/24 0024 20:27
# @File : main.py
# @Software: PyCharm

import glob
import datetime
import os
import shutil
import win32print
import win32ui
import win32con

from PIL import Image, ImageWin

def file_name():
    return datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')


def join_image(images_to_join):
    if os.path.isdir('.\\images_joined'):
        shutil.rmtree('.\\images_joined')
        os.mkdir('.\\images_joined')
    else:
        os.mkdir('.\\images_joined')
    bg = Image.new('RGB', (3508, 2479), (255, 255, 255))
    idx = 1

    for i, each in enumerate(images_to_join):
        if each.endswith('.jpg'):
            im_open = Image.open(each)
            x, y = im_open.size
            width = int(1080 * x / y)
            im_resize = im_open.resize((width, 1080), Image.ANTIALIAS)
            if idx > 6:
                bg.paste(im_resize, ((width+100)*(idx-7), 2479-1080))
            else:
                bg.paste(im_resize, ((width+100)*(idx-1), 0))
            idx += 1
            if idx == 13:
                idx = 1
                bg.save(f".\\images_joined\\{file_name()}-{i}.png")
                bg = Image.new('RGB', (3508, 2479), (255, 255, 255))

    if (i+1) % 12:
        bg.save(f".\\images_joined\\{file_name()}-{i}.png")


def print_img(file_name):

    # HORZRES / VERTRES = printable area
    #
    HORZRES = 8
    VERTRES = 10
    #
    # LOGPIXELS = dots per inch
    #
    LOGPIXELSX = 88
    LOGPIXELSY = 90
    #
    # PHYSICALWIDTH/HEIGHT = total area
    #
    PHYSICALWIDTH = 110
    PHYSICALHEIGHT = 111
    #
    # PHYSICALOFFSETX/Y = left / top margin
    #
    PHYSICALOFFSETX = 111
    PHYSICALOFFSETY = 112
    
    
    # 获取默认打印机
    printer_name = win32print.GetDefaultPrinter ()
    # printaccess = {"DesiredAccess": win32print.PRINTER_ACCESS_USE}
    # 设置权限
    printdefaults = {'DesiredAccess': win32print.PRINTER_ALL_ACCESS}
    # 打开打印机，获取当前设置
    # handle = win32print.OpenPrinter(printer_name, printdefaults)
    # win32print.ClosePrinter(handle)
    handle = win32print.OpenPrinter(printer_name, printdefaults)
    properties= win32print.GetPrinter(handle, 2)
    devmode = properties['pDevMode']
    devmode.Orientation = 2  # 横向打印
    
    # 设置横向打印
    win32print.SetPrinter(handle, 2, properties, 0)
    win32print.SetDefaultPrinter(printer_name)
    #
    # You can only write a Device-independent bitmap
    # directly to a Windows device context; therefore
    # we need (for ease) to use the Python Imaging
    # Library to manipulate the image.
    #
    # Create a device context from a named printer
    # and assess the printable size of the paper.
    #
    hDC = win32ui.CreateDC ()
    hDC.CreatePrinterDC (printer_name)
    printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
    printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)
    printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)

    #
    # Open the image, rotate it if it's wider than
    # it is high, and work out how much to multiply
    # each pixel by to get it as big as possible on
    # the page without distorting.
    #
    bmp = Image.open (file_name)
    ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
    scale = min(ratios)
    
    #
    # Start the print job, and draw the bitmap to
    # the printer device at the scaled size.
    #
    hDC.StartDoc(file_name)
    hDC.StartPage()
    
    dib = ImageWin.Dib(bmp)
    scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
    x1 = int ((printer_size[0] - scaled_width) / 2)
    y1 = int ((printer_size[1] - scaled_height) / 2)
    x2 = x1 + scaled_width
    y2 = y1 + scaled_height
    dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2))
    
    hDC.EndPage ()
    hDC.EndDoc ()
    hDC.DeleteDC ()
    # 恢复设置
    devmode.Orientation = 1  # 纵向打印
    
    # 设置横向打印
    win32print.SetPrinter(handle, 2, properties, 0)
    win32print.SetDefaultPrinter(printer_name)
    win32print.ClosePrinter(handle)


if __name__ == '__main__':
    # join_image()
    for each in glob.glob('.\\images_joined\\*'):
        print_img(each)
    

    